/**
 * @file     nextGreaterElement2.js
 * @brief    [503. 下一个更大元素 II](https://leetcode.cn/problems/next-greater-element-ii/)
 * @author   Zhu
 * @date     2024-11-28 11:08
 */

/**
 * @param {number[]} nums
 * @return {number[]}
 */
var nextGreaterElements = function (nums) {
    const n = nums.length;
    const ans = [];

    const stack = [];
    const top = () => nums[stack[stack.length - 1]];

    for (let i = 0; i < n; i++) {
        ans[i] = -1;

        while (nums[i] > top()) {
            const j = stack.pop();
            ans[j] = nums[i];
        }
        stack.push(i);
    }

    for (let i = 0; i < n; i++) {
        while (nums[i] > top()) {
            const j = stack.pop();
            ans[j] = nums[i];
        }
    }

    return ans;
};
